package com.ruoyi.web.controller.api;

import com.ruoyi.cat.domain.*;
import com.ruoyi.cat.domain.VO.AdGiftVO;
import com.ruoyi.cat.service.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(tags = "api-礼品接口")
@RestController
@RequestMapping("/api/adGiftTime")
public class AdGiftTimeController extends BaseController {

    @Autowired
    private IAdGiftService adGiftService;

    @Autowired
    private IAdGiftClassify1Service adGiftClassify1Service;

    @Autowired
    private IAdGiftClassify2Service adGiftClassify2Service;

    @Autowired
    private IAdGifiIprecordService adGifiIprecordService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IAdGiftLikeService iAdLikeRecordService;

    @Autowired
    private IAdGiftService iAdGiftService;

    @Autowired
    private ICatBannerTableService catBannerTableService;

    @Autowired
    private IAdGiftLikeService iAdGiftLikeService;

    @GetMapping("/getAdGiftClassify1")
    @ApiOperation("获取所有的活动分类")
    public AjaxResult getAdGiftClassify1(HttpServletRequest request, AdGiftClassify1 adGift1) {
        List<AdGiftClassify1> list =  adGiftClassify1Service.selectAdGiftClassify1List(adGift1);
        return success(list);
    }

    @GetMapping("/getAdGiftClassify2")
    @ApiOperation("获取所有的活动分类")
    public AjaxResult getAdGiftClassify2(HttpServletRequest request, AdGiftClassify1 adGift1) {
        AdGiftClassify2 adGiftClassify2 = new AdGiftClassify2();
        adGiftClassify2.setClassifyId(adGift1.getId());
        List<AdGiftClassify2> list2 =  adGiftClassify2Service.selectAdGiftClassify2List(adGiftClassify2);
        list2.forEach(adGiftClassify3->{
            AdGift adGift = new AdGift();
            adGift.setGiftId2(adGiftClassify3.getId());
            adGift.setState("0");
            adGiftClassify3.setAdGiftList( adGiftService.selectAdGiftListLimit(adGift));
        });
        return success(list2);
    }

    @GetMapping("/getAdGiftClassifyHome2")
    @ApiOperation("获取所有的活动分类")
    public AjaxResult getAdGiftClassifyHome2(HttpServletRequest request, AdGiftClassify1 adGift1) {
        CatBannerTable catBannerTable = new CatBannerTable();
        catBannerTable.setType(adGift1.getId());
        return success(catBannerTableService.selectCatBannerTableList(catBannerTable));
    }


    @GetMapping("/getAdGift")
    @ApiOperation("获取活动数据-分页,根据二级分类id查询")
    public TableDataInfo getAdGift(HttpServletRequest request, AdGiftClassify2 adGiftClassify2) {
        AdGift adGift = new AdGift();
        adGift.setGiftId2(adGiftClassify2.getId());
        adGift.setState("0");
        startPage();
        List<AdGift> adGifts = adGiftService.selectAdGiftList(adGift);
        return getDataTable(adGifts);
    }


    @GetMapping("/getGiftLike")
    @ApiOperation("获取喜欢列表")
    public TableDataInfo getGiftLike(HttpServletRequest request, Long userId) {
        startPage();
        List<AdGift> adGifts =  iAdGiftLikeService.getGiftLike(userId);;
        return getDataTable(adGifts);
    }



    @GetMapping("/getHotAdGifts")
    @ApiOperation("获取热门活动")
    public AjaxResult getHotAdGifts(HttpServletRequest request) {
        return success(iAdGiftService.getAdGiftList(10));
    }

    @ApiOperation("api-获取活动详情")
    @PostMapping("getAdGiftDetails")
    public AjaxResult getAdGiftDetails(HttpServletRequest request, @RequestBody AdGiftVO adConfig) {
        AdGift adGift = adGiftService.selectAdGiftByUserId(adConfig.getGiftId(),adConfig.getUserId());
        return success(adGift);
    }

    @ApiOperation("api-购买活动")
    @PostMapping("payAdGift")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult payAdGift(HttpServletRequest request, @RequestBody AdGiftVO adConfig) {
        AdGift adGift = adGiftService.selectAdGiftById(adConfig.getGiftId());
        adGift.setEmption(adGift.getEmption()+1);
        return success(adGiftService.updateAdGiftBy(adGift));
    }

    @ApiOperation("api-分享接口")
    @PostMapping("shareAdGift")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult shareAdGift(HttpServletRequest request, @RequestBody AdGiftVO adConfig) {
        AdGift adGift = adGiftService.selectAdGiftById(adConfig.getGiftId());
        adGift.setForwardNum(adGift.getForwardNum()+1);
        return success(adGiftService.updateAdGiftBy(adGift));
    }

    @ApiOperation("api-喜欢这个活动")
    @PostMapping("likeAdGift")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult likeAdGift(HttpServletRequest request, @RequestBody AdGiftVO adConfig) {
        String userId = adConfig.getUserId().toString();
        String giftId = adConfig.getGiftId().toString();

        // Redis key
        String likeSetKey = "gift:like:" + giftId;  // 存储点赞用户的集合
        String likeCountKey = "gift:count:" + giftId;  // 存储点赞总数

        // 检查用户是否已经点赞过
        Boolean isLiked = redisTemplate.opsForSet().isMember(likeSetKey, userId);

        AdGift adGift = adGiftService.selectAdGiftById(adConfig.getGiftId());

        if(isLiked != null && isLiked) {
            // 取消喜欢
            redisTemplate.opsForSet().remove(likeSetKey, userId);
            redisTemplate.opsForValue().decrement(likeCountKey);

            // 重新设置过期时间
            redisTemplate.expire(likeSetKey, 1, TimeUnit.HOURS);
            redisTemplate.expire(likeCountKey, 1, TimeUnit.HOURS);

            adGift.setLikeCount(adGift.getLikeCount()-1);

            // 删除数据库记录
            AdGiftLike adGiftLike = new AdGiftLike();
            adGiftLike.setUserId(adConfig.getUserId());
            adGiftLike.setGiftId(adConfig.getGiftId());
            List<AdGiftLike> list = iAdLikeRecordService.selectAdGiftLikeList(adGiftLike);
            if(list.size() > 0) {
                iAdLikeRecordService.deleteAdGiftLikeById(list.get(0).getId());
            }
        } else {
            // 新增喜欢
            redisTemplate.opsForSet().add(likeSetKey, userId);
            redisTemplate.opsForValue().increment(likeCountKey);

            // 设置1小时过期时间
            redisTemplate.expire(likeSetKey, 1, TimeUnit.HOURS);
            redisTemplate.expire(likeCountKey, 1, TimeUnit.HOURS);
            adGift.setLikeCount(adGift.getLikeCount()+1);
            // 插入数据库记录
            AdGiftLike adGiftLike = new AdGiftLike();
            adGiftLike.setUserId(adConfig.getUserId());
            adGiftLike.setGiftId(adConfig.getGiftId());
            iAdLikeRecordService.insertAdGiftLike(adGiftLike);
        }
        return success(adGiftService.updateAdGiftBy(adGift));
    }

    @ApiOperation("api-新增阅读量")
    @PostMapping("addReadCount")
    public AjaxResult addReadCount(HttpServletRequest request, @RequestBody AdGiftVO adConfig) {
        String ipAddress = IpUtils.getIpAddr(request);
        Long giftId = adConfig.getGiftId();

        log.info("新增阅读量 IP: {}, 活动ID: {}", ipAddress, giftId);

        // 构建Redis key，格式：gift_ip_today:活动ID:IP:日期
        String today = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date());
        String redisKey = String.format("gift_ip_today:%s:%s:%s", giftId, ipAddress, today);

        // 查询活动信息
        AdGift adGift = adGiftService.selectAdGiftById(giftId);
        if (adGift == null) {
            return error("活动不存在");
        }

        // 使用Redis检查今天是否已访问过
        Boolean hasVisited = redisTemplate.hasKey(redisKey);
        boolean isFirstVisitToday = !hasVisited;

        try {
            // 记录IP访问记录
            AdGifiIprecord adGifiIprecord = new AdGifiIprecord();
            adGifiIprecord.setIpAddress(ipAddress);
            adGifiIprecord.setCreateTime(new Date());
            adGifiIprecord.setIpConfig(giftId);

            // 如果今天第一次访问，PV设为1；否则增加PV
            if (isFirstVisitToday) {
                adGifiIprecord.setPv(1L);
            } else {
                // 获取当前PV值并增加
                  redisTemplate.opsForValue().get(redisKey);
            }

            // 插入或更新IP记录（数据库层面处理唯一约束）
            adGifiIprecordService.insertAdGifiIprecord(adGifiIprecord);

            // 更新活动统计
            // 每次访问都增加总浏览量
            adGift.setQuantity(adGift.getQuantity() + 1);

            // 只有今天第一次访问才增加独立访客数
            if (isFirstVisitToday) {
                adGift.setNumberVisitors(adGift.getNumberVisitors() + 1);
                log.info("IP: {} 今天首次访问活动: {}, 增加独立访客数", ipAddress, giftId);
            }

            // 更新活动信息
            adGiftService.updateAdGiftBy(adGift);

            // 将访问记录存入Redis，设置过期时间为今天结束
            redisTemplate.opsForValue().set(redisKey, adGifiIprecord.getPv()+"", getSecondsUntilEndOfDay(), TimeUnit.SECONDS);

            log.info("活动: {} 统计更新完成 - 总浏览量: {}, 独立访客: {}, 是否今日首访: {}",
                    giftId, adGift.getQuantity(), adGift.getNumberVisitors(), isFirstVisitToday);

        } catch (Exception e) {
            log.error("更新阅读量失败 - IP: {}, 活动ID: {}, 错误: {}", ipAddress, giftId, e.getMessage(), e);
            return error("更新阅读量失败");
        }

        return success(adGift);
    }

    /**
     * 获取到今天结束的剩余秒数
     */
    private long getSecondsUntilEndOfDay() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime endOfDay = now.with(LocalTime.MAX);
        return Duration.between(now, endOfDay).getSeconds();
    }

}
